//
//  HWAiPayInfo.m
//  嗨文
//
//  Created by 响当当 on 4/2/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "HWAiPayInfo.h"

static HWAiPayInfo *_api = nil;

#define LCUserTable @"hwApiCount"
@implementation HWAiPayInfo
/**
 *  获取支付宝账号
 */
+ (HWAiPayInfo *)currentUser
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_api) {
            _api = [[HWAiPayInfo alloc]init];
            if (![lcDBOperation lc_isExistTable:LCUserTable]) {
                [lcDBOperation lc_createTable:LCUserTable dicOrModel:self];
            }else
            {
                [_api getCurrentUserApiInfo];
            }
        }
    });
    return _api;
}


#pragma 获取当前用户支付宝信息
- (void)getCurrentUserApiInfo
{
    NSString *apiName = IFNULL(LCUserDefaultsGet(HWAiPayCount), @"");
    if ([apiName isEqualToString:@""])
    {
        NSLog(@"暂无支付宝账号信息");
    }else
    {
        NSString *sql = [NSString stringWithFormat:@"where aiPayName = %@",apiName];
        NSArray *userList = [lcDBOperation lc_lookupTable:LCUserTable dicOrModel:self whereFormat:sql];
        if (userList.count > 0) {
            _api = (HWAiPayInfo *)(userList.firstObject);
        }
    }
}

- (void)savaSessionSucess:(void(^)(void))sucess fail:(void(^)(NSError *error))fail
{
    
    
    if ([current_ApiPayCount isExistUser])
    {
        [current_ApiPayCount refreshUserInfoSucess:^{
            if (sucess) {
                sucess();
            }
        } fail:^(NSError *error) {
            
        }];
    }else
    {
        BOOL insertUserIsSucess = [lcDBOperation lc_insertTable:LCUserTable dicOrModel:current_ApiPayCount];
        if (insertUserIsSucess) {
            if (sucess) {
                sucess();
            }
        }else
        {
            NSError *error = nil;
            if (fail) {
                fail(error);
            }
        }
    }
}

-(BOOL)isExistUser
{
    NSString *sql = [NSString stringWithFormat:@"where aiPayName = %@",current_ApiPayCount.aiPayName];
    NSArray *datas = [lcDBOperation lc_lookupTable:LCUserTable dicOrModel:self whereFormat:sql];
    if (datas.count > 0) {
        return true;
    }else
    {
        return false;
    }
}

#pragma 重新更新个人信息
- (void)refreshUserInfoSucess:(void(^)(void))sucess fail:(void(^)(NSError *error))fail
{
    NSString *sql = [NSString stringWithFormat:@"where aiPayName = %@",current_ApiPayCount.aiPayName];
    if ([lcDBOperation lc_updateTable:LCUserTable dicOrModel:current_ApiPayCount whereFormat:sql]) {
        if (sucess) {
            sucess();
        }
    }else
    {
        if (fail) {
            NSError *error = nil;
            fail(error);
        }
    }
    
}
@end
